package com.hexinfo.dmpro.data.transfer.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hexinfo.dmpro.data.transfer.common.common.manager.AgentManager;
import com.hexinfo.dmpro.data.transfer.common.common.session.AgentSession;
import com.hexinfo.dmpro.data.transfer.common.dao.AgentInfoMapper;
import com.hexinfo.dmpro.data.transfer.common.model.AgentInfo;
import com.hexinfo.dmpro.data.transfer.common.service.IAgentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class AgentInfoService extends ServiceImpl<AgentInfoMapper, AgentInfo> implements IAgentInfoService {

    @Autowired
    private AgentManager agentManager;

    private AgentInfo queryByHostAndPort(String agentHost, Integer agentPort) {
        LambdaQueryWrapper<AgentInfo> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AgentInfo::getAgentHost, agentHost);
        wrapper.eq(AgentInfo::getAgentPort, agentPort);
        return this.baseMapper.selectOne(wrapper);
    }

    @Override
    @Transactional
    public void register(AgentInfo agentInfo) {
        AgentInfo dbAgentInfo = this.queryByHostAndPort(agentInfo.getAgentHost(), agentInfo.getAgentPort());
        if (dbAgentInfo != null) {
            dbAgentInfo.setMaxPoolSize(agentInfo.getMaxPoolSize());
            dbAgentInfo.setSendTime(agentInfo.getSendTime());
            this.baseMapper.updateById(dbAgentInfo);
        } else {
            this.baseMapper.insert(agentInfo);
        }
        agentManager.register(agentInfo);
    }

    @Override
    @Transactional
    public void agentHeartbeat(AgentInfo agentInfo) {
        AgentInfo dbAgentInfo = this.queryByHostAndPort(agentInfo.getAgentHost(), agentInfo.getAgentPort());
        if (dbAgentInfo == null) {
            register(agentInfo);
        } else {
            dbAgentInfo.setSendTime(agentInfo.getSendTime());
            this.baseMapper.updateById(dbAgentInfo);
            agentManager.updateAgentSession(agentInfo);
        }
    }

    @Override
    public List<AgentInfo> queryList(AgentInfo agentInfo) {
        LambdaQueryWrapper<AgentInfo> wrapper = Wrappers.lambdaQuery();
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public List<AgentSession> querySessionList() {
        if (agentManager != null) {
            return agentManager.agentSessionList();
        }
        return new ArrayList<>();
    }
}
